package com.itheima.health.service.impl;

import com.itheima.health.dao.MemberMapper;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@DubboService
@Slf4j
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;

    /**
     * @Author: 位帅帅
     * @Date: 19:48 2021/1/10
     * @Params: [member]
     * @RerurnType: com.itheima.health.pojo.Member
     * @Description: 添加或更新会员信息
     */
    @Transactional
    @Override
    public Member addOrUpdate(Member member) {
        log.info("[会员-添加/更新]member: {}", member);
        Member queryMember = new Member();
        queryMember.setPhoneNumber(member.getPhoneNumber());
        Member pojo = memberMapper.selectOne(queryMember);
        if (null != pojo) {
            member.setId(pojo.getId());
            memberMapper.updateByPrimaryKeySelective(member);
        } else {
            member.setRegTime(new Date());
            memberMapper.insertSelective(member);
        }
        member = memberMapper.selectByPrimaryKey(member.getId());
        log.info("[会员-添加/更新]member: {}", member);
        return member;
    }

    /**
     * @Author: 位帅帅
     * @Date: 20:22 2021/1/10
     * @Params: [memberId]
     * @RerurnType: com.itheima.health.pojo.Member
     * @Description: 根据id查询会员信息
     */
    @Override
    public Member findById(Integer memberId) {
        log.info("[会员-id查询]id: {}", memberId);
        Member member = memberMapper.selectByPrimaryKey(memberId);
        log.info("[会员-id查询]member: {}", member);
        return member;
    }

    /**
     * @Author: 位帅帅
     * @Date: 16:28 2021/1/14
     * @Params: [months]
     * @RerurnType: java.util.List<java.lang.Integer>
     * @Description: 根据月份列表获取会员数量列表
    */
    @Override
    public List<Integer> countByMonth(List<String> months) {
        log.info("[会员-数量]months: {}",months);
        List<Integer> countList = new ArrayList<>();
        for (String month : months) {
            String endDate = month + ".31";
            Example example = new Example(Member.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andLessThanOrEqualTo("regTime",endDate);
            int count = memberMapper.selectCountByExample(example);
            countList.add(count);
        }
        return countList;
    }
}
